/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmti.skeleton.web.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义PassThruAuthenticationFilter，主要用于处理网页超时，还原为web容器默认行为
 *
 * @author danny
 */
public class MyPassThruAuthenticationFilter extends PassThruAuthenticationFilter {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        log.debug("Path within app: " + WebUtils.getPathWithinApplication(httpServletRequest));
        log.debug("Has session? " + !(SecurityUtils.getSubject().getSession(false) == null));

        // 网页超时，session失效的情况下还原为默认的web容器的处理方式。（排除根路径和登录页面）
        if (SecurityUtils.getSubject().getSession(false) == null
                && !WebUtils.getPathWithinApplication(httpServletRequest).equals("/")
                && !WebUtils.getPathWithinApplication(httpServletRequest).equals(this.getLoginUrl())) {
            httpServletResponse.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT);
            return false;
        }
        return super.onAccessDenied(request, response);
    }

}
